<?php

namespace app\controllers\admin\uni\order;

use app\controllers\admin\AdminController;
use app\controllers\wx\services\Wx;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\order\OrderLogistics;
use app\models\product\Product;
use app\models\system\SetExpressCompany;
use app\models\system\SetWx;
use app\models\user\User;
use app\util\Request;
use app\util\Util;

class BaseController extends AdminController
{
    public function actionSaveExpress()
    {
        $company_id = $this->post('company_id');
        $express_sn = $this->post('express_sn');

        $order_id = $this->post('order_id');
        $order_item_id = $this->post('order_item_id');
        $user_address_id = $this->post('user_address_id');

        // var_dump($company_id, $express_sn, $order_id, $order_item_id, $user_address_id);

        $model = new OrderLogistics();
        $model->order_id = $order_id;
        $model->order_item_id = $order_item_id;
        $model->user_address_id = $user_address_id;
        $model->express_company_id = $company_id;
        $model->express_sn = $express_sn;
        $model->status = 1;

        if ($model->save()) {

            // result
            $logistics = OrderLogistics::find()
                ->where(['id' => $model->id])
                ->with(['company', 'address'])
                ->asArray()
                ->one();

            // order status
            $order = Order::findOne(['id' => $order_id]);
            $item_count = OrderItem::find()
                ->where(['order_id' => $order_id])
                ->andWhere(['is_express' => 1])
                ->count();
            $logistics_count = OrderLogistics::find()
                ->where(['order_id' => $order_id])
                ->count();
            if ($logistics_count >= $item_count) {
                $order->status = Order::$statusMapping['WAIT_RECEIVING'];
                $order->save();
            }

            // 对接 微信 发货
            // https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order-shipping/order-shipping.html#%E4%B8%80%E3%80%81%E5%8F%91%E8%B4%A7%E4%BF%A1%E6%81%AF%E5%BD%95%E5%85%A5%E6%8E%A5%E5%8F%A3

            // $this->wx($company_id, $express_sn, $order_id);

            return $this->success([
                'logistics' => $logistics,
                'order_status' => $order->status,
            ]);
        }

        return $this->fail();
    }

    // 对接微信API
    // todo ....
    public function wx($company_id, $express_sn, $order_id)
    {
        $access_token = Wx::getAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' . $access_token;

        // 查询小程序是否已开通发货信息管理服务
        // $url = 'https://api.weixin.qq.com/wxa/sec/order/is_trade_managed?access_token=' . $access_token;
        // $x = Request::post($url, json_encode([
        //     'appid' => SetWx::getLastOne(false)->app_id,
        // ]));
        // var_dump($x);exit;

        // 查询小程序是否已完成交易结算管理确认
        // $url = 'https://api.weixin.qq.com/wxa/sec/order/is_trade_management_confirmation_completed?access_token=' . $access_token;
        // $x = Request::post($url, json_encode([
        //     'appid' => SetWx::getLastOne(false)->app_id,
        // ]));
        // var_dump($x);exit;

        // $url = 'https://api.weixin.qq.com/wxa/sec/order/get_order_list?access_token=' . $access_token;
        // $params = [
        //       'pay_time_range' => [
        //           'begin_time' => strtotime('-1 day', time()),
        //           'end_time' => time(),
        //       ],
        //     'openid' => 'o08fs62ZVv5r1QHSlAYP38u4Fq3o'
        // ];
        // $x = Request::post($url, json_encode($params));
        //
        // var_dump($x);exit;



        $wx = SetWx::getLastOne(false);
        $mch_id = $wx->mch_id;

        $company_name = SetExpressCompany::find()
            ->where(['id' => $company_id])
            ->select(['name'])
            ->scalar();

        $company_name = 'YTO';

        if (trim($company_name) == '自提') {
            $logistics_type = 4;
        } else {
            $logistics_type = 1;
        }

        // var_dump($logistics_type);exit;

        $product_ids = OrderItem::find()
            ->where(['order_id' => $order_id])
            ->select(['product_id'])
            ->scalar();

        $product_name = Product::find()
            ->where(['id' => $product_ids])
            ->select(['title'])
            ->scalar();

        $user_id = Order::find()
            ->where(['id' => $order_id])
            ->select(['user_id'])
            ->scalar();
        $openid = User::find()
            ->where(['id' => $user_id])
            ->select(['openid'])
            ->scalar();

        // date("c", strtotime("2014-03-10 05:40:00"));
        $date = date('Y-m-d H:i:s');
        $date = date('c', strtotime($date));

        $sn = Order::find()
            ->select(['sn'])
            ->where(['id' => $order_id])
            ->scalar();

        $sn = '2025010818595144249';
        // $sn = '4200002365202501073953532330';

        // var_dump($order_id, $sn, $mch_id);exit;

        $transaction_id = '4200002570202501085368910956';

        $params = [
            'order_key' => [
                // 'order_number_type' => 1,
                // 'out_trade_no' => $sn,
                // 'mchid' => $mch_id,
                'order_number_type' => 2,
                'transaction_id' => $transaction_id,
            ],
            // 1 实体商品, 2 同城配送, 3 虚拟商品, 4 用户自提
            'logistics_type' => $logistics_type,
            // 1 统一发货, 2 分拆发货
            'delivery_mode' => 1,
            'shipping_list' => [
                [
                    // 例如：微信红包抱枕*1个，限120个字以内
                    'item_desc' => '购买商品:' . $product_name,
                    'express_company' => $company_name,
                    'tracking_no' => $express_sn,
                ]
            ],
            // `2022-12-15T13:29:35.120+08:00`
            'upload_time' => $date,
            'payer' => [
                'openid' => $openid
            ]
            // 联系方式，当发货的物流公司为顺丰时，联系方式为必填，收件人或寄件人联系方式二选一
            // 'contact' => [
            //     'consignor_contact' => '',
            //     'receiver_contact' => '',
            // ]
        ];

        // 2022-12-15T13:29:35.120+08:00
        // 2023-10-31T04:48:49+08:00

        // var_dump($params);exit;

        $params = json_encode($params);

        // var_dump($params);exit;

        $response = Request::post($url, $params);
        var_dump($response);exit;
    }
}